<template>
	<view class="route-track">
		<view class="top-tools">
			<view class="tt-date">{{sdate}} 至 {{edate}}</view>
			<view class="tt-btn">
				<u-button type="primary" size="mini" :customStyle="{'background': '#00c3ce'}">{{sb.text}}</u-button>
			</view>
		</view>
		
		<view class="map-content">
			<map 
				v-if="mapCtx"
				style="width: 100%; height: calc(100vh - 90rpx)"
				:id="mapId" 
				:longitude="longitude" 
				:latitude="latitude" 
				:scale="scale" 
				:markers="markers"
				:polyline="polyline"
				:enable-satellite="satellite" 
				:enable-rotate="true"
				:rotate="rotate"
				:show-compass="true"
				:enable-building="true"
				:show-location="true"
				:enable-overlooking="true"
			></map>
			
			<view class="btnBox">
				<u-button 
					v-if="!playSb.load"
					:custom-style="{'background': '#00c3ec', 'color': '#fff'}"
					shape="circle"
					:loading="playSb.load" 
					@click="playRouteTrack"
				>{{playSb.text}}</u-button>
				
				<!-- <u-button
					:custom-style="{'background': '#00c3ec', 'color': '#fff'}"
					shape="circle" 
					@click="roateMap"
				>旋转</u-button>-->
			</view>
		</view>
		
		<u-top-tips ref="topTips"></u-top-tips>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 地图对象id
				mapId: 'mapId_qfc',
				// 坐标点数组
				points: [],
				// 缩放级别
				scale: 14,
				// 坐标经度
				longitude: 104.065861,
				// 坐标纬度
				latitude: 30.657401,
				// 是否开启卫星图
				satellite: false,
				
				// 开始日期, 结束日期
				sdate: this.U.getSEToday()[0], edate: this.U.getSEToday()[1],
				// 搜索按钮
				sb: {load: false, text: '搜索'},
				
				// 播放路径回放按钮
				playSb: {load: false, text: '开始播放'},
				
				// 地图对象
				mapCtx: null,
				// 用于循环
				playIndex: 0, 
				// 标记点集合
				markers: [],
				// 移动的小车标记id
				moveCarId: 0,
				// 坐标点集合
				polyline: [],
				// 旋转角度
				rotate: 0,
			}
		},
		onReady() {
			// 创建map对象
			this.mapCtx = uni.createMapContext(this.mapId);
			
			// 加载完成后才加载数据
			if(this.mapCtx) this.getRouteTrackDetail();
		},
		onLoad(){
			
		},
		methods: {
			roateMap(){
				if(this.rotate >= 360) {
					this.rotate = 10;
				}else{
					this.rotate += 10;
				}
				
				console.log('当前度数', this.rotate);
			},
			// 获取-行程轨迹详情
			getRouteTrackDetail(){
				const that = this, U = that.U, C = that.C;
				
				let luser = uni.getStorageSync(C.luser);
				let ps = {
					userId: luser.userId, 
					stime: that.U.getSEToday()[0], 
					etime: that.U.getSEToday()[1],
				};
				that.$u.api.getMapPointTrackList(ps).then(res => {
					if(res.code != 1){
						U.qinfo(res.msg);
						
						that.$refs.topTips.show({
							title: '暂无轨迹数据，请稍后刷再试',
							type: 'success',
							duration: '60000'
						});
					}else{
						let list = res.data;
						
						let pos = [];
						list.forEach(it => {
							pos.push({latitude: it.lat, longitude: it.lng});
						});
						that.points = pos;
						
						// 设置初始(线路、标记)数据
						if(pos.length > 0) that.setDataByPoints(pos, 0);
					}
				}).catch(err => {console.error(err);});
			},
			// 设置-坐标地点
			setDataByPoints(pos, type) {
				let that = this, sp = pos[0];
				
				if(type == 0){
					// 移动至地图中心点
					that.mapCtx.moveToLocation({
						longitude: sp.longitude,
						latitude: sp.latitude,
						success: function(re){ console.log(re); },
						fail: function(err){ console.error(err); }
					});
					
					// 设置地图旋转角度
					let r = that.calcAngle(sp, pos[1]);
					
					// that.rotate = -r-50;
					console.log('第一个点和第二个点的角度', r);
					
					
					// 设置线路数据
					that.polyline = [{
						points: pos,
						color: '#025ADD',
						width: 4,
						dottedLine: false,
					}];
					
					// 设置标记数据
					that.markers = [{
						id: 0,
						width: 20,
						height: 30,
						latitude: sp.latitude,
						longitude: sp.longitude,
						iconPath: '/static/icons/map-car.png',
						callout: {
							content: "川A.QQ520", // 车牌信息
							display: "ALWAYS",
							fontWeight: "bold",
							color: "#ffffff", //文本颜色
							fontSize: 14,
							bgColor: "#0055ff", //背景色
							padding: 5, //文本边缘留白
							textAlign: "center",
						},
						anchor: { x: 0.5, y: 0.5},
					}];
				}else{
					// 移动至地图中心点
					that.mapCtx.moveToLocation({
						longitude: sp.longitude,
						latitude: sp.latitude,
						success: function(re){ console.log(re); },
						fail: function(err){ console.error(err); }
					});
					
					let moveCarId = that.markers[0].id;
					if(moveCarId == 0){
						that.markers[0].id = 1;
						that.moveCarId = 1;
					}else{
						that.markers[0].id = 0;
						that.moveCarId = 0;
					}
				}
				
			},
			// 平移marker，带动画
			playRouteTrack() {
				const that = this, U = that.U;
				
				let pos = that.points, cp = pos[that.playIndex], nextp = pos[that.playIndex + 1];
				
				// 获取开始点至目标点的距离
				let getDistance = that.getDistance(cp.latitude, cp.longitude, nextp.latitude, nextp.longitude);
				// 根据距离计算平移的速度，看起来保持匀速
				let duration = getDistance * 2;
				
				// 设置地图旋转角度
				// that.rotate = 300;
				
				that.playSb.load = true;
				that.mapCtx.translateMarker({
					markerId: that.moveCarId,
					autoRotate: false,
					// 旋转角度
					rotate: that.calcAngle(cp, nextp),
					destination: {
						// 车辆即将移动到的下一个点的经度
						longitude: nextp.longitude, 
						// 车辆即将移动到的下一个点的纬度
						latitude: nextp.latitude, 
					},
					duration: duration,
					complete: function(){
						that.playIndex++;
						
						if(that.playIndex < pos.length - 1){
							that.playRouteTrack();
						}else{
							// U.qinfo('播放完成');
							
							that.playIndex = 0;
							that.playSb.load = false;
							that.playSb.text = '重新播放';
							
							// 设置初始(线路、标记)数据
							that.setDataByPoints(pos, 1);
						}
					},
					animationEnd: function(e) {
						// 轨迹回放完成
						console.log('轨迹回放完成');
					},
					fail(e) {
						// 轨迹回放失败
						console.error('轨迹回放失败');
					},
				});
			},
			// 计算两坐标点之间的距离
			getDistance(lat1, lng1, lat2, lng2) {
				let rad1 = lat1 * Math.PI / 180.0;
				let rad2 = lat2 * Math.PI / 180.0;
				let a = rad1 - rad2;
				let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
				let r = 6378137;
				return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0);
			},
			// 计算两点间角度，改变图标方向
			calcAngle(start, end) {
				let y = Math.sin(end.longitude - start.longitude) * Math.cos(end.latitude);
				let x = Math.cos(start.latitude) * Math.sin(end.latitude) - Math.sin(start.latitude) * Math.cos(end.latitude) * Math.cos(end.longitude - start.longitude);
				let angle = Math.atan2(y, x);
				angle = (180 * angle) / Math.PI;
				console.log('车头角度', angle);
				return angle;
			},
			
			
		}
	}
</script>

<style lang="less">
.route-track{
	.top-tools{
		height: 90rpx;
		padding: 20rpx 10rpx;
		border-bottom: 2rpx solid #efefef;
		display: flex;
		justify-items: start;
		
		.tt-date{
			flex: 1;
		}
	}
	
	.btnBox {
		width: 750rpx;
		position: absolute;
		bottom: 60rpx;
		z-index: 99;
		display: flex;
		justify-content: space-around;
	}
}
</style>
